package com.headwind.logistics.common.controller;

import com.headwind.logistics.common.util.FileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 * @author 小恶魔
 */
@Controller
public class FileController {
    /**
     * 图片上传方法
     * @param file
     * @return
     * @throws FileNotFoundException
     */
    @PostMapping("/admin/uploadImages")
    @ResponseBody
    public Map<String,Object> projectPictureUpload(@RequestParam(value = "file",required = true) MultipartFile file,String imgPath) throws FileNotFoundException {

        Map<String,Object> map = new HashMap<>();
        //上传路径
        if (imgPath.isEmpty()){
            map.put("code",0);
            map.put("msg","上传的图片路径不能为空");
            map.put("data",null);
            return map;

        }

        //将图片上传到服务器
        if(file.isEmpty()){
            map.put("code",0);
            map.put("msg","上传的图片不能为空");
            map.put("data",null);
            return map;
        }
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //图片名称为uuid+图片后缀防止冲突
        String fileName = UUID.randomUUID().toString()+"."+suffix;

        //文件保存路径  绝对路径
        String filePath = ResourceUtils.getURL("src/main/resources/static/admin/images/"+imgPath).getPath();

        try {
            //写入图片
            Boolean writePictureflag = FileUtil.uploadFile(file.getBytes(),filePath,fileName);
            if(writePictureflag == false){
                //上传图片失败
                map.put("code",0);
                map.put("msg","上传图片失败");
                map.put("data",null);
                return map;
            }
            //上传成功后，将可以访问的完整路径返回
            String fullImgpath = "/static/admin/images/"+imgPath+"/"+fileName;
            //上传图片失败
            map.put("code",0);
            map.put("msg","上传图片成功");
            map.put("data",fullImgpath);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            //上传图片失败
            map.put("code",0);
            map.put("msg","上传图片失败");
            map.put("data",null);
            return map;
        }
    }

}
